package cn.edu.stu.syllabus.login;

import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import butterknife.BindView;
import cn.edu.stu.syllabus.R;
import cn.edu.stu.syllabus.application.SyllabusApplication;
import cn.edu.stu.syllabus.base.BaseFragment;
import cn.edu.stu.syllabus.datas.ThemeStyle;
import cn.edu.stu.syllabus.repository.token.local.TokenEntry;
import cn.edu.stu.syllabus.utils.DrawableTintUtils;
import cn.edu.stu.syllabus.utils.ToastUtils;
import cn.edu.stu.syllabus.widgets.DrawableRightClickListener;
import cn.edu.stu.syllabus.widgets.FixButtonSizeUtils;
import cn.edu.stu.syllabus.widgets.LoadingDialogBuiler;
import cn.edu.stu.syllabus.widgets.MaterialCheckBox;

import static cn.edu.stu.syllabus.utils.NullPointerUtils.checkNotNull;

/**
 * Created by daidaijie on 2017/4/23.
 */

public class LoginFragment extends BaseFragment implements LoginContract.View, LoginCallBack {

    @BindView(R.id.accountEditText)
    EditText mAccountEditText;
    @BindView(R.id.passwordEditText)
    EditText mPasswordEditText;
    @BindView(R.id.isRememberCheckBox)
    MaterialCheckBox mIsRememberCheckBox;
    @BindView(R.id.loginButton)
    Button mLoginButton;
    @BindView(R.id.checkboxLayout)
    LinearLayout mCheckboxLayout;

    private LoginListener mLoginListener;

    private AlertDialog mProgressDialog;

    private LoginContract.Presenter mPresenter;

    private boolean isPasswordHide;
    private Drawable showPasswordDrawable;
    private Drawable hidePasswordDrawable;
    private Drawable passwordDrawable;

    private Typeface monoTypeFace;

    public static LoginFragment newInstance() {
        LoginFragment loginFragment = new LoginFragment();
        return loginFragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_login;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mLoginListener = (LoginListener) mActivity;

        Drawable accountDrawable = DrawableTintUtils.getTintDrawableByColorRes(R.drawable.ic_account,
                R.color.colorAccent);
        Drawable switchAccountDrawable = DrawableTintUtils.getTintDrawableByColorRes(R.drawable.ic_switch_account,
                R.color.colorTextSecondly);
        mAccountEditText.setCompoundDrawablesWithIntrinsicBounds(
                accountDrawable, null, switchAccountDrawable, null
        );

        passwordDrawable = DrawableTintUtils.getTintDrawableByColorRes(R.drawable.ic_password,
                R.color.colorAccent);
        showPasswordDrawable = DrawableTintUtils.getTintDrawableByColorRes(R.drawable.ic_show_password,
                R.color.colorTextSecondly);
        hidePasswordDrawable = DrawableTintUtils.getTintDrawableByColorRes(R.drawable.ic_hide_password,
                R.color.colorTextSecondly);
        mPasswordEditText.setCompoundDrawablesWithIntrinsicBounds(
                passwordDrawable, null, showPasswordDrawable, null
        );
        monoTypeFace = Typeface.create("monospace", Typeface.NORMAL);

        isPasswordHide = true;
        mPasswordEditText.setOnTouchListener(new DrawableRightClickListener() {
            @Override
            public void onRightDrawableClick() {
                showPassword(isPasswordHide);
                isPasswordHide = !isPasswordHide;
            }
        });

        mCheckboxLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIsRememberCheckBox.callOnClick();
            }
        });

        mProgressDialog = LoadingDialogBuiler.buildLoadingDialog(mActivity,
                ContextCompat.getColor(SyllabusApplication.getContext(),
                        ThemeStyle.getCurrentColorPrimaryLight()), "正在登录");

        FixButtonSizeUtils.fixButtonSize(mLoginButton);
        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkLogin()) {
                    mProgressDialog.show();
                    mLoginListener.onLogin(
                            mAccountEditText.getText().toString(),
                            mPasswordEditText.getText().toString()
                    );
                }
            }
        });

        mPresenter.subscribe();
    }

    @Override
    public void onDestroyView() {
        mPresenter.unsubscribe();
        super.onDestroyView();
    }

    private boolean checkLogin() {
        boolean notInputAccount = mAccountEditText.getText().toString().isEmpty();
        boolean notInputPassword = mPasswordEditText.getText().toString().isEmpty();
        boolean isCheckPermissions = mIsRememberCheckBox.isChecked();

        if (!notInputAccount && !notInputPassword && isCheckPermissions) {
            return true;
        } else if (notInputAccount && notInputPassword) {
            ToastUtils.getInstance().showToast(
                    ToastUtils.ToastType.WARNING, "请输入账号和密码", Toast.LENGTH_SHORT
            );
        } else if (notInputAccount) {
            ToastUtils.getInstance().showToast(
                    ToastUtils.ToastType.WARNING, "请输入账号", Toast.LENGTH_SHORT
            );
        } else if (notInputPassword) {
            ToastUtils.getInstance().showToast(
                    ToastUtils.ToastType.WARNING, "请输入密码", Toast.LENGTH_SHORT
            );
        } else if (!isCheckPermissions) {
            ToastUtils.getInstance().showToast(
                    ToastUtils.ToastType.WARNING, "同意授权后才能进行登录", Toast.LENGTH_SHORT
            );
        }
        return false;
    }

    private void showPassword(boolean isShow) {
        if (isShow) {
            mPasswordEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            mPasswordEditText.setCompoundDrawablesWithIntrinsicBounds(
                    passwordDrawable, null, hidePasswordDrawable, null
            );
            mPasswordEditText.setSelection(mPasswordEditText.getText().length());
        } else {
            mPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT |
                    InputType.TYPE_TEXT_VARIATION_PASSWORD);
            mPasswordEditText.setCompoundDrawablesWithIntrinsicBounds(
                    passwordDrawable, null, showPasswordDrawable, null
            );
            mPasswordEditText.setSelection(mPasswordEditText.getText().length());
        }
        mPasswordEditText.setTypeface(monoTypeFace);
    }

    @Override
    public void onCodeGetSuccess(String code) {
        mPresenter.loadToken(code);
    }

    @Override
    public void onCodeGetFail() {
        hideProgressDialog();
        ToastUtils.getInstance().showToast(
                ToastUtils.ToastType.ERROR, "账号或者密码错误", Toast.LENGTH_SHORT
        );
    }

    @Override
    public void onTimeOut() {
        hideProgressDialog();
        ToastUtils.getInstance().showToast(
                ToastUtils.ToastType.ERROR, "登录超时", Toast.LENGTH_SHORT
        );
    }

    @Override
    public void onUnknowHost(String url) {
        hideProgressDialog();
        ToastUtils.getInstance().showToast(
                ToastUtils.ToastType.ERROR, "登录失败", Toast.LENGTH_SHORT
        );
    }

    public void hideProgressDialog() {
        if (isAdded() && mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onPostMany() {
        hideProgressDialog();
        ToastUtils.getInstance().showToast(
                ToastUtils.ToastType.ERROR, "请求过于频繁，请过一段时间再进行登录", Toast.LENGTH_SHORT
        );
    }

    @Override
    public void onUnconnect() {
        hideProgressDialog();
        ToastUtils.getInstance().showToast(
                ToastUtils.ToastType.ERROR, "网络断开", Toast.LENGTH_SHORT
        );
    }

    @Override
    public void setPresenter(LoginContract.Presenter presenter) {
        mPresenter = checkNotNull(presenter);
    }

    @Override
    public void showSuccess(TokenEntry tokenEntry) {
        hideProgressDialog();
        ToastUtils.getInstance().showToast(
                ToastUtils.ToastType.SUCCESS, "登录成功", Toast.LENGTH_SHORT
        );
    }

    @Override
    public void showFail() {
        hideProgressDialog();
        ToastUtils.getInstance().showToast(
                ToastUtils.ToastType.ERROR, "登录失败", Toast.LENGTH_SHORT
        );
    }
}
